package com.kaikeba.dao.Impl;

import com.kaikeba.dao.BaseAdminDao;
import com.kaikeba.util.DruidUtil;

import java.sql.*;
import java.util.Date;

public class AdminDaoMySql implements BaseAdminDao {
    private static final String SQL_UPDATE_LOGIN_TIME = "UPDATE EADMIN SET LOGINTIME=?,LOGINIP=? WHERE USERNAME=?";
    private static final String SQL_LOGIN = "SELECT ID FROM EADMIN WHERE USERNAME=? AND PASSWORD=?";

    /**
     * 根据管理员用户名更新登录时间和ip
     *
     * @param username 管理员用户名
     * @param date
     * @param ip
     */
    @Override
    public void updateLoginTime(String username, Date date, String ip) {
        //获取连接
        Connection conn = DruidUtil.getConnection();
        PreparedStatement statement = null;
        //预编译SQL语句
        try {
            //填充参数
            statement = conn.prepareStatement(SQL_UPDATE_LOGIN_TIME);
            statement.setDate(1,new java.sql.Date(date.getTime()));
            statement.setString(2,ip);
            statement.setString(3,username);
            //执行
            statement.executeUpdate();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            //释放资源
            DruidUtil.close(conn,statement);
        }
    }

    /**
     * 管理员根据账号密码登录
     *
     * @param username 账号
     * @param password 密码
     * @return 登录结果，true表示登录成功，false表示登录失败
     */
    @Override
    public boolean login(String username, String password) {
        //获取连接
        Connection conn = DruidUtil.getConnection();
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        //预编译SQL语句
        try {
            //填充参数
            statement = conn.prepareStatement(SQL_LOGIN);
            statement.setString(1,username);
            statement.setString(2,password);
            resultSet = statement.executeQuery();
            //有结果返回true
            return resultSet.next();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            //释放资源
            DruidUtil.close(conn,statement,resultSet);
        }
        return false;
    }
}
